//
//  UIColor+Lc.m
//  18Birdies
//
//  Created by Lc on 15/3/31.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import "LcPreconditions.h"
#import "UIColor+Lc.h"

@implementation UIColor (Lc)

+ (UIColor*)colorWithHexString:(NSString*)hexString {
  LC_CHECK_TRUE(hexString.length == 6 || hexString.length == 8);

  NSRange range = NSMakeRange(0, 2);
  NSString* alpha = @"FF";
  if (hexString.length == 8) {
    alpha = [hexString substringWithRange:range];
    range = NSMakeRange(range.location + 2, 2);
  }
  NSString* red = [hexString substringWithRange:range];
  range = NSMakeRange(range.location + 2, 2);
  NSString* green = [hexString substringWithRange:range];
  range = NSMakeRange(range.location + 2, 2);
  NSString* blue = [hexString substringWithRange:range];

  unsigned int a, r, g, b;
  LC_CHECK_TRUE([[NSScanner scannerWithString:alpha] scanHexInt:&a]);
  LC_CHECK_TRUE([[NSScanner scannerWithString:red] scanHexInt:&r]);
  LC_CHECK_TRUE([[NSScanner scannerWithString:green] scanHexInt:&g]);
  LC_CHECK_TRUE([[NSScanner scannerWithString:blue] scanHexInt:&b]);

  return [self colorWithRed:(float)r / 255.0f
                      green:(float)g / 255.0f
                       blue:(float)b / 255.0f
                      alpha:(float)a / 255.0f];
}

+ (UIColor*)colorWithHexString:(NSString*)hexString cached:(BOOL)cached {
  return [self colorWithHexString:hexString];
}

@end
